// This code is licensed under New BSD Licence. For details see project page at
// http://code.google.com/p/hrissan-cocoa-helpers/source/checkout
#import "Common.h"
#import <CommonCrypto/CommonDigest.h>
#import <Security/Security.h>

#ifdef __IPHONE_OS_VERSION_MIN_REQUIRED
#import <UIKit/UIKit.h>
#endif

NSString * calculate_md5( NSString *str )
{	
	const char *cStr = [str UTF8String];
	
	unsigned char result[CC_MD5_DIGEST_LENGTH];
	
	CC_MD5( cStr, strlen(cStr), result );
	
	return [NSString stringWithFormat: @"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
			result[0], result[1],
			result[2], result[3],
			result[4], result[5],
			result[6], result[7],
			result[8], result[9],
			result[10], result[11],
			result[12], result[13],
			result[14], result[15]
			];	
}

bool parseNSString( NSObject * obj, NSPtr<NSString> & result )
{
	NSString * val = objective_c_cast<NSString>(obj);
	if( !val )
		return false;
	result = val;
	return true;
}

bool parseLongLong( NSObject * obj, long long & result )
{
	NSNumber * val = objective_c_cast<NSNumber>(obj);
	if( !val )
		return false;
	result = [val longLongValue];
	return true;
}

bool parseInt( NSObject * obj, int & result )
{
	NSNumber * val = objective_c_cast<NSNumber>(obj);
	if( !val )
		return false;
	result = [val intValue];
	return true;
}


static int counter = 0;

void start_network_indicator()
{
	counter += 1;
#ifdef __IPHONE_OS_VERSION_MIN_REQUIRED
	[UIApplication sharedApplication].networkActivityIndicatorVisible = (counter != 0);
#endif
}

void stop_network_indicator()
{
	counter -= 1;
#ifdef __IPHONE_OS_VERSION_MIN_REQUIRED
	[UIApplication sharedApplication].networkActivityIndicatorVisible = (counter != 0);
#endif
}

NSString * get_bundle_version()
{
    NSString * vtxt = objective_c_cast<NSString>( [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"] );
    return vtxt ? vtxt : @"?";
}

NSString * get_system_version()
{
#ifdef __IPHONE_OS_VERSION_MIN_REQUIRED
    NSString * ver = [[UIDevice currentDevice] systemVersion];
    NSString * mod = [[UIDevice currentDevice] model];
    return [NSString stringWithFormat:@"%@ (%@)", ver, mod];
#else
 SInt32 versionMajor = 0;
 SInt32 versionMinor = 0;
 SInt32 versionBugFix = 0;
 Gestalt( gestaltSystemVersionMajor, &versionMajor );
 Gestalt( gestaltSystemVersionMinor, &versionMinor );
 Gestalt( gestaltSystemVersionBugFix, &versionBugFix );
 return [NSString stringWithFormat:@"%d.%d.%d", versionMajor, versionMinor, versionBugFix];
#endif
}

bool is_system_below(NSString *reqSysVer)
{
#ifdef __IPHONE_OS_VERSION_MIN_REQUIRED
	NSString *currSysVer = [[UIDevice currentDevice] systemVersion];
	
	return [currSysVer compare:reqSysVer options:NSNumericSearch] < 0;
#else
    return false;
#endif
}

NSString * mac_iphone_get_place_for_files(NSString * app_name)
{
#ifdef __IPHONE_OS_VERSION_MIN_REQUIRED
    NSString * documents_dir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    return documents_dir;
#else
    NSString * documents_dir = [NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    documents_dir = [documents_dir stringByAppendingPathComponent:app_name];
    
    NSError * error = 0;
    BOOL exists = [[NSFileManager defaultManager]
                    createDirectoryAtPath:documents_dir
                    withIntermediateDirectories:YES
                    attributes:nil
                    error:&error];
    if( !exists )
        [NSException raise:@"Could not create Application Support folder" format:@"full path=%@", documents_dir];
    return documents_dir;
#endif
}

static bool srandomed = false;

void mac_iphone_SecRandomCopyBytes(int len, uint8_t * bytes)
{
#ifdef __IPHONE_OS_VERSION_MIN_REQUIRED
    if( SecRandomCopyBytes(kSecRandomDefault, len, bytes) != 0 ) // Stupid iPhone OS :)
#endif
    {
        if( !srandomed )
        {
            srandomdev(); // will most likely fail also.
            srandomed = true;
        }
        for(int i = 0; i != len; ++i)
            bytes[i] = random() % 256;
    }
}
